<?php
/**
 * 《报价信息》实现类
 *
 * @author 孙晓晔
 * @version $Id: Info.class.php 1043 2010-04-01 08:04:38Z sunxy $
 */
require_once(dirname(__FILE__) . '/QuoteUtil.class.php');

class QuoteInfo extends QuoteUtil {
	public $tbl = Constant::tbl_quote_info;

	public $type_option = array(
		'-' => '请选择',
		'1' => '需求',
		'2' => '报价',
	);

	public $orderby = array(
		'-' => '请选择',		
		'mold' => '项目',
		'emp' => '操作人',

		'1' => '创建时间',
		'2' => '更新时间',
	);

	var $info_dir = 'quote';

	function __construct() {
		$request['update'] = '$Date: 2009/02/16 07:36:07 $';
		$request['revision'] = '$Revision: 1.1 $';

		parent::__construct($request);
	}

	function pretreat($controller) {
		parent::pretreat($controller);

		$controller->assign_by_ref('type_option', $this->type_option);
	}

	/**
	 *
	 *
	 * @param Controler $controller
	 * @param array $request
	 */
	function find($controller, $request) {
		$this->pretreat($controller);

		// $controller->assign('t1', strtotime('-1 month'));

		$controller->display($request, 'customer/quote/info/find');
		return true;
	}

	function _orderby_x($controller, $row, $px) {
		$orderby = $this->orderby['1'];
		$row['orderby_x'] = $row['createtime'];

		if (empty($px) || $px == '-' || $px == '1') {
			$controller->assign('orderby', $orderby);

			return $row;
		}

		if ($px == '2') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['modifytime'];
		}

		if ($px == '`join`') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['join'];
		}

		$controller->assign('orderby', $orderby);

		return $row;
	}

	function _is_quote($quote) {
		if (empty($quote)) {
			return true;
		}

		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE id = '%s'";
		$sql = sprintf($fmt, Constant::tbl_quote, $quote);
		// debug($sql);
		$result = $db->query($sql);
		if ($row = $db->fetch_array($result)) {
			if ($row['emp'] == $_SESSION['id']) {
				return false;
			}
		}

		return true;
	}

	function _where($request) {
		$quote_s = $this->_input($request['quote_s']);

		$type_s = $request['type_s'];

		$my = $this->_my();
		$where = " WHERE 1=1";

		if (!empty($quote_s)) {
			$where .= " AND quote = '" . $quote_s . "'";
		}

		if (!empty($my) && $this->_is_quote($quote_s)) {
			$where .= " AND " . $my;
		}

		if (!empty($type_s) && $type_s <> '-') {
			$where .= " AND type = " . $type_s;
		}

		$where .= $this->_where_default($request);
		$where = $this->_where_aa($where);

		return $where;
	}

	/**
	 *
	 *
	 * @param Controler $controller
	 * @param array $request
	 */
	function findPost($controller, $request) {
		$this->pretreat($controller);

		$this->findPara($controller, $request);

		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s a %s %s";
		$where = $this->_where($request);
		$orderby = $this->_orderby();		
		$sql = sprintf($fmt, $this->tbl, $where, $orderby);
		debug($sql);

		$pager_option = array (
            'db' => $db,
            'sql' => $sql,
            'PageSize' => $this->pagesize,
            'CurrentPageID' => $request['p'],
            'numItems' => $request['n']
		);

		$pager = @new Pager($pager_option);
		$data = $pager->getPageData();

		if ($pager->number > 0) {

			$count = 0;
			$from = $pager->from;
			while ($count < $pager->number) {
				$row = $data[$count];
				$row = $this->_view(null, $row);
				
				$row['file'] = $this->_file_exist($row['id']);

				$row = $this->_orderby_x($controller, $row, $this->orderby_s);

				$data[$count] = $row;
				$count++;
			}
			$controller->assign_by_ref('result', $data);
			$controller->assign_by_ref('pager', $pager);
		}

		$controller->assign('emp', $_SESSION['id']);
		$controller->assign('empname', $_SESSION['name']);


		if ($this->_is_admin()) {
			$controller->display($request, 'customer/quote/info/admin/list');
		} else {
			$controller->display($request, 'customer/quote/info/list');
		}
		return true;
	}
	
	function _quote_code($id) {
		$row = $this->id(Constant::tbl_quote, $id);

		return $row['code'];
	}

	/**
	 * 添加
	 *
	 * @param Controler $controller
	 * @param array $request
	 */
	function add($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];

		require_once 'Quote.class.php';
		$quote = new Quote();
		$controller->assign_by_ref('quote', $quote->_view($id));

		$controller->display($request, 'customer/quote/info/add');
		return true;
	}

	/**
	 * 上传附件
	 *
	 * @param Controler $controller
	 * @param array $request
	 */
	function addPost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];

		$quote = $this->id(Constant::tbl_quote, $id);

		$requote = $request['requote'];
		$content = addslashes($request['content']);

		$type = $request['type'];
		if (empty($type) || $type == '-') {
			$type = '1';
		}

		$num = $request['num'];

		$db = newdb($this->dsn_w);
		$fmt = "INSERT INTO %s(customer, quote, mold, type, content, bj, emp, oper, createtime)";
		$fmt .= " VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', now())";
		$sql = sprintf($fmt, $this->tbl, $quote['customer'], $id, $quote['code'], $type, $content, $quote['bj'], $quote['emp'], $_SESSION['id']);
		// debug($sql);
		$db->query($sql);

		$ret = array('id'=> $db->insert_id());

		$this->_quote($controller, $request, $quote, $type, $requote);

		if (!empty($num) && $num <> $quote['num']) {
			$fmt = "UPDATE %s SET num = '%s' WHERE id = '%s'";
			$sql = sprintf($fmt, Constant::tbl_quote, $num, $id);
			$db->query($sql);
		}

		echo json_encode($ret);
		return true;
	}

	function ajax_upload($controller, $request) {
		require_once 'HTTP/Upload.php';
		$upload = new HTTP_Upload('en');
		$file = $upload->getFiles('Filedata');
		if (PEAR::isError($file)) {
			die($file->getMessage());
		}

		if ($file->isValid()) {
			$now = date('Y-m-d H:i:s');

			$id = $request['id'];
			$name = $request['name'];
			if (empty($name) || $name == '-') {
				$name = 'uniq';
			}

			$dir = Download::dir($this->info_dir, $now, $id);
			// debug($dir);
			if (!@file_exists($dir)) {
				umask();
				mkdir($dir, 0777, true);
			}

			$file->setName($name);
			$filename = $file->moveTo($dir);
			if (PEAR::isError($filename)){
				die($filename->getMessage());
			}

			$filesize = $file->upload['size'];

			$db = newdb($this->dsn);
			$fmt = "INSERT INTO %s(info, name, size, createtime)";
			$fmt .= " VALUES('%s', '%s', '%s', now())";
			$sql = sprintf($fmt, Constant::tbl_quote_file, $id, $filename, $filesize);
			debug($sql);
			$db->query($sql);
		}

		echo "1";
		return true;
	}

	function _quote($controller, $request, $row, $type, $requote) {
		if ($type == '2') {
			$status = '8';
		} else {
			$status = '2';
		}

		if (empty($requote)) {
			$times = $row['times'];
		} else {
			$times = intval($row['times']) + 1;
		}

		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET times = '%s', status = '%s' WHERE id = '%s'";
		$sql = sprintf($fmt, Constant::tbl_quote, $times, $status, $row['id']);
		// debug($sql);
		$db->query($sql);

		require_once 'Quote.class.php';
		$quote = new Quote();
		$quote->_notice_x($controller, $request, $row['id']);

		clean(Constant::tbl_quote . "_id_" . $row['id']);
	}

	function sendmail_($from, $to, $subject, $body) {
		echo "Sendmail...\n";

		$header = "From: " . $from . "\r\n";
		$header .= "Content-Type: text/html; charset=utf-8\r\n";
		$header .= "Content-Transfer-Encoding: base64";

		$subject = "=?utf-8?B?" . base64_encode($subject) . "?=";
		$body = chunk_split(base64_encode($body));

		mail($to, $subject, $body, $header);
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function edit($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		require_once 'Quote.class.php';
		$quote = new Quote();
		$controller->assign_by_ref('quote', $quote->_view($row['quote']));

		$controller->assign_by_ref('file', $this->_file($row));

		$controller->display($request, 'customer/quote/info/edit');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function editPost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];

		$content = addslashes($request['content']);

		$status = $request['status'];

		$db = newdb($this->dsn);
		$fmt = "UPDATE %s SET content = '%s', modifytime = now() WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $content, $id);
		// debug($sql);
		$db->query($sql);
		if ($db->error()) {
			$controller->assign("msg", "修改失败，请联系管理员" . $db->error());
			$controller->display($request, 'info');
			return false;
		}

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function view($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		require_once 'Quote.class.php';
		$quote = new Quote();
		$controller->assign_by_ref('quote', $quote->_view($row['quote']));

		$controller->assign_by_ref('file', $this->_file($row));

		$controller->display($request, 'customer/quote/info/view');
		return true;
	}
	
	function _view($id = 0, $row = null) {
		if ($row == null) {
			clean($this->tbl . "_id_" . $id);
			$row = $this->id($this->tbl, $id);
		}

		$row['quote_t'] = $this->_quote_code($row['quote']);
		$row['customer_t'] = Name::customer($row['customer']);
		
		$row['type_t'] = $this->type_option[$row['type']];
				
		$row = $this->_view_t($row);
		
		return $row;
	}

	/**
	 * 删除
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function delete($controller, $request) {
		$this->pretreat($controller);

		$db = newdb($this->dsn);
		while (list($k, $id) = each($request)) {
			if (substr($k, 0, 2) <> "c_") {
				continue;
			}

			clean($this->tbl . "_id_" . $id);
			$row = $this->id($this->tbl, $id);
			if ($this->is_delete($row['quote'])) {
				continue;
			}

			$dir = Download::dir($this->info_dir, $row['createtime'], $row['quote']);
			$file = $dir . $row['filename'];
			if (@file_exists($file)) {
				@unlink($file);
			}

			$this->dir_clean($dir);

			$fmt = "delete from %s WHERE id = '%s'";
			$sql = sprintf($fmt, $this->tbl, $id);
			// debug($sql);
			$db->query($sql);

			$this->reset($row['quote']);
		}

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	/**
	 * 判断是否可以删除，其中正在报价、暂停报价、完成报价是不可以删除的
	 *
	 * @param integer $id
	 * @return boolean
	 */
	function is_delete($id) {
		$row = $this->id(Constant::tbl_quote, $id);

		$status = $row['status'];
		if ($status == '3') {
			return true;
		}

		if ($status == '5') {
			return true;
		}

		if ($status == '8') {
			return true;
		}

		return false;
	}
	
	function _update_bj($quote, $bj) {
		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET bj = '%s', modifytime = now() WHERE quote = '%s'";
		$sql = sprintf($fmt, $this->tbl, $bj, $quote);
		// debug($sql);
		$db->query($sql);
	}

	/**
	 * 状态复位至申请
	 *
	 * @param Integer $quote
	 * @return boolean
	 */
	function reset($quote) {
		if ($this->exist_info($quote)) {
			return true;
		}

		$row = $this->id(Constant::tbl_quote, $quote);
		if ($row['status'] <> '2') {
			return true;
		}

		clean(Constant::tbl_quote . "_id_" . $quote);

		$db = newdb($this->dsn);
		$fmt = "UPDATE %s SET status = '1' WHERE id = '%s'";
		$sql = sprintf($fmt, Constant::tbl_quote, $quote);
		// debug($sql);
		$db->query($sql);

		return false;
	}

	function _file($data) {
		$db = newdb(Constant::tbl_quote_file);
		$fmt = "SELECT * FROM %s WHERE info = '%s' ORDER BY id DESC";
		$sql = sprintf($fmt, Constant::tbl_quote_file, $data['id']);
		// debug($sql);
		$result = $db->query($sql);

		$ret = array();
		while ($row = $db->fetch_array($result)) {
			$row['file'] = Download::url($this->info_dir, $data['createtime'], $data['id'], $row['name']);
			$row['size_t'] = printsize($row['size']);

			$ret[] = $row;
		}

		return $ret;
	}

	function _file_exist($id) {
		$db = newdb(Constant::tbl_quote_file);
		$fmt = "SELECT * FROM %s WHERE info = '%s' ORDER BY id DESC";
		$sql = sprintf($fmt, Constant::tbl_quote_file, $id);
		// debug($sql);
		$result = $db->query($sql);
		if ($db->num_rows($result) > 0) {
			return true;
		}

		return false;
	}

	function t($controller, $request) {
		$db = newdb($this->dsn);

		$fmt = "SELECT * FROM %s limit 2";
		$sql = sprintf($fmt, $this->tbl);
		echo $sql;
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			// print_r($row);
			$dir1 = $this->_dir($this->info_dir, $row['createtime'], $row['quote']);
			$dir2 = $this->_dir($this->info_dir, $row['createtime'], $row['id']);

			$fmt = "mv %s %s\n";
			$cmd = sprintf($fmt, $dir1, $dir2);
			echo $cmd;
			// shell_exec($cmd);
		}

		logdate($controller, $request);
		return true;
	}

	function _dir($type, $date, $id) {
		$dd = date('Y/m/d', strtotime($date));

		$fmt = "%s/upload/tt/%s/%s/%s/";
		$dir = sprintf($fmt, '/home/ftp/tecmold.com/ns/trunk', $type, $dd, $id);

		return $dir;
	}
	
	function move_emp($from, $to) {
		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET emp = '%s' WHERE emp = '%s'";
		$sql = sprintf($fmt, $this->tbl, $to, $from);
		debug($sql);
		$db->query($sql);
	}
	
	function move_id_emp($quote, $to) {
		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET emp = '%s' WHERE quote = '%s'";
		$sql = sprintf($fmt, $this->tbl, $to, $quote);
		debug($sql);
		$db->query($sql);
	}
}
?>